package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IJingfeiDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 经费管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-04-10
 */
@Service
public class JingfeiDetailServiceImpl implements IJingfeiDetailService 
{
    @Autowired
    private static SysDictDataMapper sysDictDataMapper;

    @Autowired
    private ZhuanjiaMapper zhuanjiaMapper;

    @Autowired
    private DeptZhuanjiaMapper deptZhuanjiaMapper;

    @Autowired
    private DeptidOlddeptidServiceImpl deptidOlddeptidService;

    @Autowired
    private ZhuanjiaBiandongDetailMapper zhuanjiaBiandongDetailMapper;

    @Autowired
    private ZhuanjiaBiandongHistoryMapper zhuanjiaBiandongHistoryMapper;

    @Autowired
    private JisuangongshiService jisuangongshiService;

    @Autowired
    private JingfeiPiciMapper jingfeiPiciMapper;

    @Autowired
    private JingfeiDetailMapper jingfeiDetailMapper;

    private List<String> tingfazhuangtaiList = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8");

    /**
     * 查询经费管理
     * 
     * @param id 经费管理主键
     * @return 经费管理
     */
    @Override
    public JingfeiDetail selectJingfeiDetailById(String id)
    {
        return jingfeiDetailMapper.selectJingfeiDetailById(id);
    }

    /**
     * 查询经费管理列表
     * 
     * @param jingfeiDetail 经费管理
     * @return 经费管理
     */
    @Override
    public List<JingfeiDetail> selectJingfeiDetailList(JingfeiDetail jingfeiDetail)
    {
        return jingfeiDetailMapper.selectJingfeiDetailList(jingfeiDetail);
    }

    /**
     * 新增经费管理
     * 
     * @param jingfeiDetail 经费管理
     * @return 结果
     */
    @Override
    public int insertJingfeiDetail(JingfeiDetail jingfeiDetail)
    {
        return jingfeiDetailMapper.insertJingfeiDetail(jingfeiDetail);
    }

    /**
     * 修改经费管理
     * 
     * @param jingfeiDetail 经费管理
     * @return 结果
     */
    @Override
    public int updateJingfeiDetail(JingfeiDetail jingfeiDetail)
    {
        return jingfeiDetailMapper.updateJingfeiDetail(jingfeiDetail);
    }

    /**
     * 批量删除经费管理
     * 
     * @param ids 需要删除的经费管理主键
     * @return 结果
     */
    @Override
    public int deleteJingfeiDetailByIds(String ids)
    {
        return jingfeiDetailMapper.deleteJingfeiDetailByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除经费管理信息
     * 
     * @param id 经费管理主键
     * @return 结果
     */
    @Override
    public int deleteJingfeiDetailById(String id)
    {
        return jingfeiDetailMapper.deleteJingfeiDetailById(id);
    }

    /**
     * 计算专家应该发放津贴金额
     * 计算所属单位的专家津贴金额
     *
     * @param jingfeipiciId 经费批次ID
     * @param deptId        单位ID
     * @param zhuanjiaId    专家ID
     * @return 返回专家津贴金额
     */
    @Override
    @Transactional
    public int jisuanzhuanjiajintie(String jingfeipiciId, String deptId, String zhuanjiaId, String nowDeptId, int isjisuan) {

        System.out.println("zhuanjiaid:"+zhuanjiaId);

        int ok = 1;
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        ZoneId zoneId = ZoneId.systemDefault();//系统时区

        JingfeiDetail jingfeiDetail = jingfeiDetailMapper.selectAllByZhuangjiaidAndJingfeipiciIdAndDeptId(zhuanjiaId, deptId, jingfeipiciId);
        if (isjisuan == 1) {
            JingfeiPici jingfeiPici = jingfeiPiciMapper.selectJingfeiPiciById(jingfeipiciId);//当前批次信息
            LocalDateTime jisuanshijian = jingfeiPici.getJisuanshijian().toInstant().atZone(zoneId).toLocalDateTime();//计算时间，将Date类型转换为LocalDate
            LocalDateTime kaishishijian = jingfeiPici.getKaishinianyue().toInstant().atZone(zoneId).toLocalDateTime();//批次开始时间，将Date类型转换为LocalDate
            LocalDateTime jieshushijian = jingfeiPici.getJieshunianyue().toInstant().atZone(zoneId).toLocalDateTime();//批次结束时间，将Date类型转换为LocalDate

            if (jingfeiDetail == null) {
                jingfeiDetail = new JingfeiDetail();
                jingfeiDetail.setId(UUID.randomUUID().toString());
                jingfeiDetail.setZhuangjiaid(zhuanjiaId);
                jingfeiDetail.setDeptid(deptId);
                jingfeiDetail.setJingfeipiciid(jingfeipiciId);
                jingfeiDetail.setJingfeipicimingcheng(jingfeiPiciMapper.selectJingfeiPiciById(jingfeipiciId).getJingfeipicimingcheng());
                jingfeiDetail.setIsbufa(0);
                jingfeiDetail.setIstingfa(0);
                jingfeiDetail.setIsquane(1);
                jingfeiDetail.setIsshoudao(0);
                jingfeiDetail.setIsvalid(1);
                jingfeiDetail.setBeizhu1(dateTimeFormatter.format(kaishishijian));
                jingfeiDetail.setBeizhu2(dateTimeFormatter.format(jieshushijian));
                if (jingfeiDetailMapper.insertJingfeiDetail(jingfeiDetail) != 1)
                    throw new RuntimeException("insert detail" + deptId + "error");
            }

            jingfeiDetail.setJingfeipiciid(jingfeipiciId);
            jingfeiDetail.setJingfeipicimingcheng(jingfeiPiciMapper.selectJingfeiPiciById(jingfeipiciId).getJingfeipicimingcheng());


            ZhuanjiaBiandongDetail idAndIstongguo = new ZhuanjiaBiandongDetail();//用来查询专家变动详细信息的条件实体:专家id和是否通过




            LocalDateTime tingfashijian = jingfeiDetailMapper.selectTingfashijianByZhuanjiaId(zhuanjiaId, deptId,
                    jingfeipiciId, dateTimeFormatter.format(kaishishijian));//上次发放津贴给专家的时间
            LocalDateTime shangcifafangshijian = null;

            DeptZhuanjia deptZhuanjia = deptZhuanjiaMapper.selectDeptZhuanjiaByDeptIdAndZhuanjiaId(deptId, zhuanjiaId);

            if (tingfashijian != null)
                shangcifafangshijian = tingfashijian;
//            else if (deptZhuanjia.getBiangengshijian() == null) {
            else
                shangcifafangshijian = jingfeiPici.getKaishinianyue().toInstant().atZone(zoneId).toLocalDateTime().minusMonths(1);
//            }
//            else if (deptZhuanjia.getBiangengshijian().toInstant().atZone(zoneId).toLocalDateTime().isAfter(jieshushijian))
//                shangcifafangshijian = jieshushijian;
//            else if (deptZhuanjia.getBiangengshijian() != null)
//                shangcifafangshijian = deptZhuanjia.getBiangengshijian().toInstant().atZone(zoneId).toLocalDateTime();

            idAndIstongguo.setZhuanjiaid(zhuanjiaId);
            idAndIstongguo.setBeizhu1("1");

            List<ZhuanjiaBiandongDetail> zhuanjiaBiandongDetailList;


            //如果计算时间在批次截至日期之前
            if (jisuanshijian.isBefore(jieshushijian)) {
                //获取专家未使用的变动数据
                zhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper.selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(zhuanjiaId, deptId, "0", "1", jisuanshijian.format(dateTimeFormatter), jieshushijian.format(dateTimeFormatter));

                getZhuanjiaMoney(jingfeiDetail, nowDeptId, zoneId, zhuanjiaId, shangcifafangshijian, zhuanjiaBiandongDetailList, jisuanshijian, kaishishijian, jieshushijian);

//            shenpiTimeAndId.setZhuanjiaid(zhuanjiaId);
//            shenpiTimeAndId.setBiandongshijian(lastChangeDetail.getShenpishijian());
//            lastHistory = zhuanjiaBiandongHistoryMapper.selectZhuanjiaBiandongHistory(shenpiTimeAndId);

            } else {

                zhuanjiaBiandongDetailList = zhuanjiaBiandongDetailMapper.selectZhuanjiaBiandongDetailListByZhuanjiaIdAndDeptIdAndUsedAndTongguoOrJieshuTime(zhuanjiaId, deptId, "0", "1", jieshushijian.format(dateTimeFormatter), jieshushijian.format(dateTimeFormatter));

                getZhuanjiaMoney(jingfeiDetail, nowDeptId, zoneId, zhuanjiaId, shangcifafangshijian,
                        zhuanjiaBiandongDetailList, jisuanshijian, kaishishijian, jieshushijian);
            }

//        Zhuanjia zhuanjia = new Zhuanjia();
//        zhuanjia.setZhuanjiaid(zhuanjiaId);

            System.out.println("------专家姓名：" + zhuanjiaMapper.selectZhuanjiaByZhuanjiaid(zhuanjiaId).getXingming());
            if (jingfeiDetailMapper.updateJingfeiDetail(jingfeiDetail) != 1) {
                ok = 0;
                throw new RuntimeException("update jingfeidetail :" + jingfeiDetail.getId() + "error");
            }
        } else
            ok = 0;
        return ok;
    }

    /**
     * 单位拨款详情 专家list
     * @param map
     * @return 专家列表
     */
    @Override
    public List<Map> selectZhuanjiaList(Map<String, Object> map) {
        return jingfeiDetailMapper.selectZhuanjiaList(map);
    }


    /**
     * 具体的计算专家津贴方法
     *
     * @param zoneId                     时区
     * @param shangcifafangshijian       上次给专家发放津贴时间
     * @param zhuanjiaBiandongDetailList 专家未使用的变动数据
     * @param jisuanshijian              专家中心计算
     * @param jieshushijian
     * @return
     */
    //需要优化
    private int getZhuanjiaMoney(JingfeiDetail jingfeiDetail, String nowDeptId, ZoneId zoneId, String zhuanjiaId,
                                 LocalDateTime shangcifafangshijian, List<ZhuanjiaBiandongDetail> zhuanjiaBiandongDetailList,
                                 LocalDateTime jisuanshijian, LocalDateTime kaishishijian, LocalDateTime jieshushijian) {
        LocalDateTime biangengshijian = null;
        ZhuanjiaBiandongDetail lastChangeDetail = null;
        double zhuanjiaMoney;
        Date newShangcifafangshijian = Date.from(jieshushijian.atZone(zoneId).toInstant());
        //查询单位和专家关联表
        DeptZhuanjia deptZhuanjia = deptZhuanjiaMapper.selectDeptZhuanjiaByDeptIdAndZhuanjiaId(
                jingfeiDetail.getDeptid(), zhuanjiaId);
//        ZhuanjiaBiandongHistory zhuanjiaBiandongHistory = new ZhuanjiaBiandongHistory();//专家变动历史
//        zhuanjiaBiandongHistory.setZhuanjiaid(zhuanjiaId);
//        zhuanjiaBiandongHistory.setIsvalid(1L);

        //获取最近一次专家变动数据
        if (zhuanjiaBiandongDetailList != null && zhuanjiaBiandongDetailList.size() > 0) {
            lastChangeDetail = zhuanjiaBiandongDetailList.get(0);
            biangengshijian = lastChangeDetail.getBiandongriqi().toInstant().atZone(zoneId).toLocalDateTime();
//            zhuanjiaBiandongHistory.setBiandongshijian(lastChangeDetail.getBiandongriqi());
        } else if (deptZhuanjia.getBiangengshijian() != null)
            biangengshijian = deptZhuanjia.getBiangengshijian().toInstant().atZone(zoneId).toLocalDateTime();

//        //查询变动的历史记录
//        ZhuanjiaBiandongHistory lastZhuanjiaBiandongHistory = zhuanjiaBiandongHistoryMapper
//                .selectZhuanjiaBiandongHistory(zhuanjiaBiandongHistory);


        jingfeiDetail.setIstingfa(0);
        jingfeiDetail.setIsquane(1);
        double bufajine;
        List<Double> zongjineAndBufajine;
        //没有变动的专家“正常”发
        if (lastChangeDetail == null && deptZhuanjia.getBiangengshijian() == null) {
            zongjineAndBufajine = jisuangongshiService.zhengchangfafang(kaishishijian, jieshushijian, shangcifafangshijian);
            //变动状态为12345678的专家停发
        } else if (deptZhuanjia.getBiangengshijian() != null && deptZhuanjia.getIsvalid() == 2L || tingfazhuangtaiList.contains(lastChangeDetail.getBiandongleixing())) {
            if (deptZhuanjia.getIsvalid() == 2L) {
                zongjineAndBufajine = jisuangongshiService.tingfafafang(kaishishijian,
                        deptZhuanjia.getBiangengshijian().toInstant().atZone(zoneId).toLocalDateTime(), jisuanshijian, shangcifafangshijian);
                if (jingfeiDetail.getDeptid().equals(nowDeptId)) {
                    deptZhuanjia.setIsvalid(0L);
                    if (deptZhuanjiaMapper.updateDeptZhuanjia(deptZhuanjia) != 1)
                        throw new RuntimeException("更新专家与单位关系错误" + zhuanjiaId);
                }
            }
            else
                zongjineAndBufajine = jisuangongshiService.tingfafafang(kaishishijian,
                        biangengshijian, jisuanshijian, shangcifafangshijian);
            newShangcifafangshijian = Date.from(biangengshijian.atZone(zoneId).toInstant());
            jingfeiDetail.setIstingfa(1);
            jingfeiDetail.setIsquane(0);
        } else {
            //如果专家变更前状态是转出，则上次发放时间为转出时间
                //如果专家在同一批次转入转出，则判断专家和单位的状态，如果是2，则表示是专家转出的单位
            if (deptZhuanjia.getBiangengshijian() != null)
                zongjineAndBufajine = jisuangongshiService.bufafafang(biangengshijian, kaishishijian, jieshushijian,
                        jisuanshijian, deptZhuanjia.getBiangengshijian().toInstant().atZone(zoneId).toLocalDateTime());
            else
                zongjineAndBufajine = jisuangongshiService.bufafafang(biangengshijian, kaishishijian, jieshushijian,
                        jisuanshijian, shangcifafangshijian);
            jingfeiDetail.setIstingfa(0);
            jingfeiDetail.setIsquane(0);
        }

        zhuanjiaMoney = zongjineAndBufajine.get(0);
        bufajine = zongjineAndBufajine.get(1);
        //如果现在计算的单位是专家所属单位，则更新专家上次发放时间
//        if (jingfeiDetail.getDeptid().equals(nowDeptId)) {
//            jingfeiDetail.setTingfanianyue(newShangcifafangshijian);
//            if (deptZhuanjia.getIsvalid().equals("2")) {
//                deptZhuanjia.setIsvalid(0L);
//                deptZhuanjiaMapper.updateDeptZhuanjia(deptZhuanjia);
//            }
//
//        }
        jingfeiDetail.setTingfanianyue(newShangcifafangshijian);

        jingfeiDetail.setShifajine(zhuanjiaMoney);
        jingfeiDetail.setBufajine(bufajine);
        if (bufajine > 0)
            jingfeiDetail.setIsbufa(1);
        return 1;
    }
}
